原始題目如下:(6kyu)
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples.
翻譯:
統計按讚人數,顯示不同的文字格式。(共五種版本)
範例:
likes [] -- must be "no one likes this"
likes ["Peter"] -- must be "Peter likes this"
likes ["Jacob", "Alex"] -- must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] -- must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] -- must be "Alex, Jacob and 2 others like this"
function likes(names) {
let len = names.length;
let result = ''
switch (len) {
case 0:
result = 'no one likes this'
break;
case 1:
result = `${names[0]} likes this`
break;
case 2:
result = `${names[0]} and ${names[1]} like this`
break;
case 3:
result = `${names[0]}, ${names[1]} and ${names[2]} like this`
break;
default:
result = `${names[0]}, ${names[1]} and ${names.length-2} others like this`
break;
}
return result
}
土法煉鋼switch-case
,計算按讚人數,將5種格式一一列出。重複很高,強迫症不要看
function likes(names) {
return {
0: 'no one likes this',
1: `${names[0]} likes this`,
2: `${names[0]} and ${names[1]} like this`,
3: `${names[0]}, ${names[1]} and ${names[2]} like this`,
4: `${names[0]}, ${names[1]} and ${names.length - 2} others like this`,
}[Math.min(4, names.length)]
}
將顯示文字形式以物件Object
儲存,以objectName.propertyName
取得value。
function likes (names) {
var templates = [
'no one likes this',
'{name} likes this',
'{name} and {name} like this',
'{name}, {name} and {name} like this',
'{name}, {name} and {n} others like this'
];
var idx = Math.min(names.length, 4);
return templates[idx].replace(/{name}|{n}/g, function (val) {
return val === '{name}' ? names.shift() : names.length;
});
}
先把所有的版本存在templates
陣列中,由Math.min()
決定是哪一個版本,將人名{name}或人數{n}做替換。
先前在Vowel Count這篇有整理到replace()
,回顧自己常用的用法還是str.replace(substr,newSubstr)
居多。
剛好這篇使用到str.replace(regexp,function)
來一一替換{name}
或{n}
:
/{name}|{n}/g
搜尋template中的{name} or {n}{name}
,替換成names陣列中第一個元素names.shift()
會移除並回傳陣列第一個元素
(即names陣列本身會被異動){n}
,替換成names陣列目前個數以上為今日分享的內容,若有錯誤或是建議,請再隨時和我聯繫。